package com.yhh.college_information_platform.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yhh.college_information_platform.common.PageResult;
import com.yhh.college_information_platform.common.ResultCode;
import com.yhh.college_information_platform.entity.DownloadRecord;
import com.yhh.college_information_platform.entity.Resource;
import com.yhh.college_information_platform.exception.BusinessException;
import com.yhh.college_information_platform.mapper.DownloadRecordMapper;
import com.yhh.college_information_platform.mapper.ResourceMapper;
import com.yhh.college_information_platform.service.DownloadRecordService;
import com.yhh.college_information_platform.vo.DownloadRecordVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.DecimalFormat;
import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 下载记录Service实现类
 *
 * @author yhh
 * @date 2025-10-25
 */
@Slf4j
@Service
public class DownloadRecordServiceImpl implements DownloadRecordService {

    @Autowired
    private DownloadRecordMapper downloadRecordMapper;

    @Autowired
    private ResourceMapper resourceMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addDownloadRecord(Long userId, Long resourceId, String ip) {
        // 1. 检查资料是否存在
        Resource resource = resourceMapper.selectById(resourceId);
        if (resource == null) {
            throw new BusinessException(ResultCode.PARAM_ERROR, "资料不存在");
        }

        // 2. 添加下载记录
        DownloadRecord record = new DownloadRecord();
        record.setUserId(userId);
        record.setResourceId(resourceId);
        record.setDownloadIp(ip);
        record.setDownloadTime(LocalDateTime.now());
        downloadRecordMapper.insert(record);

        log.info("用户 {} 下载了资料 {}", userId, resourceId);
    }

    @Override
    public PageResult<DownloadRecordVO> getUserDownloadRecords(Long userId, Integer current, Integer size) {
        // 1. 查询用户的下载记录
        LambdaQueryWrapper<DownloadRecord> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DownloadRecord::getUserId, userId)
                .orderByDesc(DownloadRecord::getDownloadTime);
        
        Page<DownloadRecord> page = new Page<>(current, size);
        Page<DownloadRecord> recordPage = downloadRecordMapper.selectPage(page, wrapper);

        // 2. 转换为VO
        List<DownloadRecordVO> voList = recordPage.getRecords().stream()
                .map(record -> {
                    DownloadRecordVO vo = new DownloadRecordVO();
                    vo.setId(record.getId());
                    vo.setResourceId(record.getResourceId());
                    vo.setDownloadTime(record.getDownloadTime());
                    
                    // 查询资料信息
                    Resource resource = resourceMapper.selectById(record.getResourceId());
                    if (resource != null) {
                        vo.setResourceTitle(resource.getTitle());
                        vo.setFileName(resource.getFileName());
                        vo.setFileType(resource.getFileType());
                        vo.setFileSize(formatFileSize(resource.getFileSize()));
                    }
                    
                    return vo;
                })
                .collect(Collectors.toList());

        return new PageResult<>(voList, recordPage.getTotal(), recordPage.getSize(), recordPage.getCurrent());
    }

    /**
     * 格式化文件大小
     */
    private String formatFileSize(Long size) {
        if (size == null || size == 0) {
            return "0 B";
        }
        
        DecimalFormat df = new DecimalFormat("#.##");
        if (size < 1024) {
            return size + " B";
        } else if (size < 1024 * 1024) {
            return df.format(size / 1024.0) + " KB";
        } else if (size < 1024 * 1024 * 1024) {
            return df.format(size / (1024.0 * 1024.0)) + " MB";
        } else {
            return df.format(size / (1024.0 * 1024.0 * 1024.0)) + " GB";
        }
    }
}

